package com._54programer.demo.packet.problem;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author SN
 * @date 2019/11/28
 * @description netty客户端
 */
public class NettyClient {

    public static void main(String[] args) throws Exception {

        //创建一个事件循环组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class) //客户端通道实现类
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new NettyClientHandler());//往pipeline管道加入自己定义的处理器
                        }
                    });
            //连接服务器
            ChannelFuture cf = bootstrap.connect("127.0.0.1", 10001).sync();
            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }

}
